package com.skytech.utils;

import lombok.extern.slf4j.Slf4j;
import ws.schild.jave.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class AudioUtils {

    /**
     * 获取audio文件信息
     * @param audioFile
     * @return
     */
    public static MultimediaInfo getAudioInfo(File audioFile){
        MultimediaObject multimediaObject = new MultimediaObject(audioFile);
        try {
            return multimediaObject.getInfo();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * jave分离左右双声道录音
     * @param orginalFilePath
     * @param leftFilePath
     * @param rightFilePath
     * @return
     */
    public static File[] doubleChannelSpite(String orginalFilePath, String leftFilePath, String rightFilePath){
        File leftFile = new File(leftFilePath);
        File rightFile = new File(rightFilePath);
        if (leftFile.exists()) {
            leftFile.delete();
        }
        if (rightFile.exists()) {
            rightFile.delete();
        }

        DefaultFFMPEGLocator locator = new DefaultFFMPEGLocator();
        System.out.println("execute path : " + locator.getFFMPEGExecutablePath());
        FFMPEGExecutor ffmpeg = locator.createExecutor();
        ffmpeg.addArgument("-i");
        ffmpeg.addArgument(orginalFilePath);
        ffmpeg.addArgument("-map_channel");
        ffmpeg.addArgument("0.0.0");
        ffmpeg.addArgument(leftFilePath);
        ffmpeg.addArgument("-map_channel");
        ffmpeg.addArgument("0.0.1");
        ffmpeg.addArgument(rightFilePath);

        BufferedReader br = null;
        try {
            ffmpeg.execute();
            br = new BufferedReader(new InputStreamReader(ffmpeg.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null){
                log.info(line);
            }
            return new File[]{leftFile, rightFile};
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(null != br){
                    br.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }

}
